/*
 * @Author:Iyoole
 * @Time  :2018-01-29
 * @Description:表格
 * @git:
 * */

;!function(e) {
    "use strict";
    var i,r={
        index:0
    };
    var Table=function(elem){
        this.elem=i(elem);
        r.index++
    };
    Table.pt=Table.prototype;
    Table.pt.config={
        limit:10,
        cellWidth:60,
        text:'无数据'
    };
    Table.pt.render=function(opts){
        var t=this;
        t.config=i.extend(true,{},t.config,opts);
        t.setArea();
        t.create();
        t.fullSize();
        t.pullData();
        t.events();
    };
    Table.pt.setArea=function(){//计算宽高
        var t=this,tc=t.config.cols;
        var pw=t.config.width||function(){//容器宽度
            var getWidth = function(parent){
                var width, isNone;
                parent = parent || t.elem;
                width = parent.width();
                try {
                    isNone = parent.css('display') === 'none';
                } catch(e){}
                if(parent[0] && (!width || isNone)) return getWidth(parent.parent());
                return width;
            };
            return getWidth();
        }();
        pw=pw-tc.length-1;
        var autoArr=[],//记录没有标记宽的列
            countWidth=0;//已用列宽
        i.each(tc,function(m,n){
            if(!n.width){
                autoArr.push(m)
            }else{
                countWidth+=n.width
            }
        });
        if(autoArr.length>0){//如果有没标记的,剩余宽度平分给它们
            if(pw>countWidth){
                i.each(autoArr,function(m,n){
                    tc[n]['width']=(pw-countWidth)/autoArr.length>t.config.cellWidth?(pw-countWidth)/autoArr.length:t.config.cellWidth
                });
            }else{
                i.each(autoArr,function (m,n) {
                    tc[n]['width']=t.config.cellWidth
                })
            }
            t.autoArr=1;
        }else{
            if(pw>countWidth){
                var jf=Math.floor((pw-countWidth)/tc.length);
                i.each(tc,function(m,n){
                    if(m==tc.length-1){
                        n['width']=pw-countWidth-m*jf+n['width']
                    }else{
                        n['width']=n['width']+jf
                    }
                })
            }
        }
    };
    Table.pt.create=function(){
        var t=this,td=t.config;
        var $View=i('<div/>').addClass('fui-table-view').appendTo(t.elem),
            $Box=i('<div/>').addClass('fui-table-box').appendTo($View),
            $Header=i('<div/>').addClass('fui-table-header').appendTo($Box),
            $Body=i('<div/>').addClass('fui-table-body').appendTo($Box);
        var tableHeader='<table class="fui-table"><thead><tr>'+function(){
                var th='';
                i.each(td.cols,function(m,n){
                    th+='<th data-field="'+n.field+'"><div class="fui-table-cell fuiTable-cell-'+r.index+'-'+n.field+'">'+(n.title?n.title:n.field)+'</div></th>'
                });
                return th
            }()+'</tr></thead></table>';
        $Header.append(tableHeader);
        var tableBody='<table class="fui-table"><tbody></tbody></table>';
        $Body.append(tableBody);
        var style='<style>'+function(){
                var sCss='';
                i.each(td.cols,function(m,n){
                    sCss+='.fuiTable-cell-'+r.index+'-'+n.field+'{width:'+n.width+'px}'
                });
                return sCss
            }()+'</style>';
        $View.append(style);
        t.$Box=$Box;
        t.$Header=$Header;
        t.$Main=$Body;//后面填充处理要用
        t.$page=i('<div/>').addClass('fui-table-page-'+r.index);
    };
    Table.pt.pullData=function(page){
        var t=this;
        var od={page:1||page};
        // i.ajax({
        //     type:t.config.method||'get',
        //     url:t.config.url,
        //     dataType:'json',
        //     data:i.extend(true,{},od,t.config.data),
        //     success:function(res){
        //         if(res.code==1){
        //             t.renderData(res.result['records']?res.result['records']:res.result);
        //         }else{
        //             layer?layer.msg('返回数据异常!'):console.error('返回数据异常!');
        //         }
        //     },
        //     error:function(){
        //         layer?layer.msg('请求失败!'):console.error('请求失败!');
        //     }
        // });
        var total=5;
        var rd=[{id:9001,name:'iyoole',sex:1},{id:9002,name:'Starry',sex:1},{id:9010,name:'尚小羊',sex:2},{id:9002,name:'Starry',sex:1},{id:9010,name:'尚小羊',sex:2},{id:9009,name:'张三',sex:1},{id:9005,name:'李四',sex:1},{id:9015,name:'荆小六',sex:2},{id:9105,name:'荆小七',sex:2}];
        t.renderData(rd);
        if(total>t.config.limit){
            t.page=1;
            t.$page.appendTo(t.$Box);
            //开启分页功能
        }
    };
    Table.pt.renderData=function(rd){
        var t=this,tr='';
        i.each(rd,function(x,y){
            tr+='<tr>'+function(){
                    var td='';
                    i.each(t.config.cols,function(m,n){
                        var nV=y[n.field];
                        if(n["fun"]){
                            nV=n.fun(nV)
                        }
                        td+='<td><div class="fui-table-cell fuiTable-cell-'+r.index+'-'+n.field+'">'+nV+'</div></td>'
                    });
                    return td
                }()+'</tr>'
        });
        t.$Main.find('tbody').empty().append(tr);
        t.scrollPatch();
    };

    //获取cssRule
    Table.pt.getCssRule = function(field, callback){
        var that = this
            ,style = that.elem.find('style')[0]
            ,sheet = style.sheet || style.styleSheet || {}
            ,rules = sheet.cssRules || sheet.rules;
        i.each(rules,function(m,n){
            if(n.selectorText===('.fuiTable-cell-'+r.index+'-'+field)){
                return callback(n),true;
            }
        });
    };
    Table.pt.fullSize = function(){
        var t = this,options = t.config,height = options.height, bodyHeight;
        bodyHeight = parseFloat(height) - 42;
        if(options.page){
            bodyHeight = bodyHeight - t.$page.outerHeight() - 1;
        }
        t.$Main.css('height', bodyHeight);
    };
    //获取滚动条宽度
    Table.pt.getScrollWidth = function(elem){
        var width = 0;
        if(elem){
            width = elem.offsetWidth - elem.clientWidth;
        } else {
            elem = document.createElement('div');
            elem.style.width = '100px';
            elem.style.height = '100px';
            elem.style.overflowY = 'scroll';

            document.body.appendChild(elem);
            width = elem.offsetWidth - elem.clientWidth;
            document.body.removeChild(elem);
        }
        return width;
    };

    //滚动条补丁
    Table.pt.scrollPatch = function(){
        var that = this
            ,layMainTable = that.$Main.children('table')
            ,scrollWidth = that.$Main.width() - that.$Main.prop('clientWidth') //纵向滚动条宽度
            ,scrollHeight = that.$Main.height() - that.$Main.prop('clientHeight') //横向滚动条高度
            ,getScrollWidth = that.getScrollWidth(that.$Main[0]) //获取主容器滚动条宽度，如果有的话
            ,outWidth = layMainTable.outerWidth() - that.$Main.width(); //表格内容器的超出宽度

        //如果存在自动列宽，则要保证绝对填充满，并且不能出现横向滚动条
        if(that.autoArr && outWidth < 5 && !that.scrollPatchWStatus){
            var th = that.$Header.eq(0).find('thead th:last-child')
                ,field = th.data('field');
            that.getCssRule(field, function(item){
                var width = item.style.width || th.outerWidth();
                item.style.width = (parseFloat(width) - getScrollWidth - outWidth) + 'px';

                //二次校验，如果仍然出现横向滚动条
                if(that.$Main.height() - that.$Main.prop('clientHeight') > 0){
                    item.style.width = parseFloat(item.style.width) - 1 + 'px';
                }

                that.scrollPatchWStatus = true;
            });
        }

        if(scrollWidth && scrollHeight){
            if(!that.elem.find('.fui-table-patch')[0]){
                var patchElem = i('<th class="fui-table-patch"><div class="fui-table-cell"></div></th>'); //补丁元素
                patchElem.find('div').css({
                    width: scrollWidth
                });
                that.$Header.eq(0).find('thead tr').append(patchElem)
            }
        } else {
            that.$Header.eq(0).find('.fui-table-patch').remove();
        }
    };

    Table.pt.events=function(){
        var that = this
            ,options = that.config
            ,_BODY = i('body')
            ,dict = {}
            ,resizing
            ,th = that.$Header.find('th');
        //拖拽调整宽度
        th.on('mousemove', function(e){
            var ot = i(this)
                ,oLeft = ot.offset().left
                ,pLeft = e.clientX - oLeft;
            dict.allowResize = ot.width() - pLeft <= 10; //是否处于拖拽允许区域
            _BODY.css('cursor', (dict.allowResize ? 'col-resize' : ''));
        }).on('mouseleave', function(){
            if(dict.resizeStart) return;
            _BODY.css('cursor', '');
        }).on('mousedown', function(e){
            var ot = i(this);
            if(dict.allowResize){
                var field = ot.data('field');
                e.preventDefault();
                dict.resizeStart = true; //开始拖拽
                dict.offset = [e.clientX, e.clientY]; //记录初始坐标

                that.getCssRule(field, function(item){
                    var width = item.style.width || ot.outerWidth();
                    dict.rule = item;
                    dict.ruleWidth = parseFloat(width);
                    dict.minWidth = ot.data('minwidth') || options.cellWidth;
                });
            }
        });
        //拖拽中
        i(document).on('mousemove', function(e){
            if(dict.resizeStart){
                e.preventDefault();
                if(dict.rule){
                    var setWidth = dict.ruleWidth + e.clientX - dict.offset[0];
                    if(setWidth < dict.minWidth) setWidth = dict.minWidth;
                    dict.rule.style.width = setWidth + 'px';
                }
                resizing = 1
            }
        }).on('mouseup', function(){
            if(dict.resizeStart){
                dict = {};
                _BODY.css('cursor', '');
                that.scrollPatch();
            }
            if(resizing === 2){
                resizing = null;
            }
        });

        that.$Main.on('scroll', function(){
            var ot = i(this)
                ,scrollLeft = ot.scrollLeft();

            that.$Header.scrollLeft(scrollLeft);
        });

        i(window).on('resize', function(){ //自适应
            that.fullSize();
            that.scrollPatch();
        });
    };



    var JsTable=function(elem){
        return new Table(elem)
    };
    JsTable.v='1.0';
    if(window.fui && fui.define ){
        fui.define('jquery', function(exports){
            e.JsTable=JsTable;
            i=fui.$;
            exports('JsTable', JsTable);
        });
    }else{//如果直接引用的话
        e.JsTable=JsTable;
        i=e.jQuery;
    }
}(window);


/*
* 1.0版
* 暂只处理单行表头
*
* */




